package com.sky.controller.admin;


import com.sky.dto.DishDTO;
import com.sky.dto.PageDTO;
import com.sky.entity.Dish;
import com.sky.query.DishQuery;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品相关模块")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @ApiOperation("添加菜品接口")
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("添加菜品：{}",dishDTO);

        dishService.save(dishDTO);

        String key = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(key);

        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("分页查询接口")
    public Result<PageDTO<DishVO>> queryPage(DishQuery dishQuery){
        log.info("分页查询条件：{}",dishQuery);
        PageDTO<DishVO> pageDTO = dishService.queryPage(dishQuery);

        return Result.success(pageDTO);
    }

    @DeleteMapping
    @ApiOperation("批量删除菜品")
    public Result deleteByIds(@RequestParam List<Long> ids){
        log.info("批量删除菜品：{}",ids);
        dishService.deleteByIds(ids);

        cleanCache("dish_*");

        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询菜品接口")
    public Result<DishVO> queryById(@PathVariable Long id){
        log.info("根据ID查询菜品：{}",id);
        DishVO dishVO = dishService.queryById(id);
        return Result.success(dishVO);
    }

    @PutMapping
    @ApiOperation("修改菜品信息接口")
    public Result updateDish(@RequestBody DishDTO dishDTO){
        log.info("根据ID查询菜品：{}",dishDTO);
        dishService.updateDish(dishDTO);

        cleanCache("dish_*");

        return Result.success();
    }

    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售、停售接口")
    public Result startOrStop(@PathVariable Integer status, @RequestParam("id")Long id){
        log.info("菜品起售、停售：{}",id);
        dishService.updateStatus(status,id);
        cleanCache("dish_*");
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品接口")
    public Result<List<DishVO>> listByCategoryId(Long categoryId){
        log.info("根据分类ID查询菜品：{}",categoryId);
        List<DishVO> dishList = dishService.listByCategoryId(categoryId);
        return Result.success(dishList);
    }

    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
